import Koa from 'koa'
import { blobTobase64, fileToBytes } from '../utils/blobUtils'
import invoiceDal from '../dal/invoiceDal'
import { isEmptyObject } from '../utils/is'
import dayjs from 'dayjs'

interface InvoiceRes {
  id: number
  userName: string | null
  userNickName: string | null
  createTime: string
  file: string
}

class InvoiceController {
  async uploadinvoice(ctx: Koa.Context) {
    // 解析Token获取用户信息
    const token = ctx.request.headers['auth-token']
    if (!token) {
      ctx.fail('token已过期', 500)
    }
    // console.log(ctx.request.files, ctx.request.body)
    const { userId, departmentId } = ctx.request.body
    const { file } = ctx.request.files as any
    // console.log(file, fileToBytes(file))

    if (file) {
      try {
        await invoiceDal.addInvoice({
          content: fileToBytes(file),
          userId: Number(userId),
          departmentId: Number(departmentId)
        })
        ctx.success('file')
      } catch (error) {
        console.log(error)
        ctx.fail(error, 550)
      }
    } else {
      ctx.fail('缺少文件', 501)
    }
  }

  async getInvoiceList(ctx: Koa.Context) {
    const searchParams = ctx.request.body

    const data = await invoiceDal.getInvoiceList(
      isEmptyObject(searchParams) ? null : searchParams
    )
    console.log(data)
    const res: InvoiceRes[] = []
    data.forEach((invoice) => {
      const temp: InvoiceRes = {
        id: invoice.id,
        userName: invoice.user.name,
        userNickName: invoice.user.nickname,
        createTime: dayjs(invoice.createdAt).format('YYYY-MM-DD HH:MM'),
        file: ''
      }
      const buffer = Buffer.from(invoice.content)
      const base64String = buffer.toString('base64')

      temp.file = base64String
      res.push(temp)
    })

    ctx.success(res, '成功')
  }
}

export default new InvoiceController()
